package com.yawn.zerodefect.controller.interceptor;

import com.yawn.zerodefect.controller.IdentityController;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Created by yawn on 2018-02-02 14:44
 */
@Component
public class IndexInterceptor implements HandlerInterceptor {

    @Resource
    private IdentityController identityController;

    private static final String DEFAULT_INDEX_URI = "/index";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (DEFAULT_INDEX_URI.equals(uri)) {
            HttpSession session = request.getSession();
            String redirectUri = "/about";
            if (identityController.isDeveloper(session)
                    || identityController.isTester(session)
                    || identityController.isRequire(session)) {
                redirectUri = "/defect";
            } else if (identityController.isManager(session)){
                redirectUri = "/user";
            }
            response.sendRedirect(redirectUri);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 不用实现
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 不用实现
    }
}
